package com.weijing.pretty_app.util

import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext

/**
 * @param hz 页面的HZ值
 * @param initNum 首页初始化得到的统计发射次数
 */
class WorkTimerController(
    private val hz: Int, // 频率 HZ，例如 10
    private val initNum: Int, //首页初始化得到的统计发射次数
    private val onSendCommand: (workCount: Int) -> Unit,
    private val onFinish: () -> Unit
) : CoroutineScope {

    private val job = SupervisorJob()

    override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob()

    private var elapsedSeconds = 0
    private var timerJob: Job? = null
    private var isRunning = false

    fun start() {
        if (isRunning) return
        isRunning = true
        timerJob = launch {
            while (isActive) {
                delay(1000L)
                elapsedSeconds++

                val workCount = elapsedSeconds * hz + initNum
                if (workCount >= KeyUtil.MAX_COUNT) {
                    stopInternal()
                    onFinish()
                    break
                }

                /*if (elapsedSeconds % 60 == 0) { //一分钟通知一次
                    onSendCommand(workCount)
                    Log.i("计时的秒数", "workCount- $workCount")
                }*/
                //每秒通知一次
                onSendCommand(workCount)
            }
        }
    }

    fun pause() {
        if (!isRunning) return

        isRunning = false
        timerJob?.cancel()

        val workCount = elapsedSeconds * hz + initNum
        onSendCommand(workCount)
    }

    fun reset() {
        pause()
        elapsedSeconds = 0
    }

    fun getElapsedSeconds(): Int = elapsedSeconds

    fun release() {
        pause()
        job.cancel()
    }

    private fun stopInternal() {
        isRunning = false
        timerJob?.cancel()
    }
}